package com.tm.szb.filter;

import com.alibaba.fastjson.JSON;
import com.tm.szb.commons.R;
import com.tm.szb.commons.ResultEnums;
import com.tm.szb.config.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
@Slf4j
public class LoginFilter implements Filter {

    //路径匹配器，支持通配符
   private static AntPathMatcher antPathMatcher = new AntPathMatcher();

   private static final String[] urls = {
           "/employee/login",
           "/employee/logout",
           "/backend/**",
           "/front/**",
           "/static/**",
   };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =  (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        String requestURI = request.getRequestURI();
        if (checkUrl(urls,requestURI)) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        Object employee = request.getSession().getAttribute("employee");
        if (employee == null){
            //表示没有登陆过
            log.info("没有登录的用户，不能进行访问");
            response.getWriter().write(JSON.toJSONString(R.error(ResultEnums.NOT_LOGIN)));
            return;
        }

        //将登陆用户的id存入到当前上下文
        ThreadLocalUtils.setThreadLocal((Long)employee);
        //表示由用户已经登陆过，执行下一个过滤器
        filterChain.doFilter(servletRequest,servletResponse);
    }

    /**
     *路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean checkUrl(String[] urls, String requestURI) {

        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match){
                return Boolean.TRUE;
            }
        }
            return Boolean.FALSE;
    }
}
